package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.mapper.BrandMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    /**
     * 分页查询品牌数据
     * @param page
     * @param rows
     * @param key
     * @param sortBy
     * @param desc
     * @return
     */
    public PageResult<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key, String sortBy, Boolean desc) {
        //1.分页
        PageHelper.startPage(page,rows);

        //2.构建查询条件
        //2.1过滤条件
        Example example = new Example(Brand.class);
        if (StringUtils.isNoneBlank(key)){
            example.createCriteria()
                    .orLike("name","%" + key + "%")//拼接模糊查询
                    .orEqualTo("letter",key);//拼接等值查询
        }

        //2.2排序方式
        if(StringUtils.isNoneBlank(sortBy)){
            String orderByClause = sortBy + (desc ? " DESC" : " ASC");
            example.setOrderByClause(orderByClause);//id desc
        }

        //3.查询
        List<Brand> brands = brandMapper.selectByExample(example);
        //3.1判断是否为空
        if (CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }

        //4.返回品牌数据
        //4.1解析分页结果
        PageInfo<Brand> info = new PageInfo<>(brands);
        //4.2转换成BrandDTO
        List<BrandDTO> brandDTOS = BeanHelper.copyWithCollection(brands,BrandDTO.class);
        //4.3返回
        return new PageResult<>(info.getTotal(),info.getPages(),brandDTOS) ;
    }

    /**
     * 新增品牌
     * @param brandDTO
     * @param ids
     */
    @Transactional
    public void saveBrand(BrandDTO brandDTO, List<Long> ids) {
        //新增品牌
        Brand brand = BeanHelper.copyProperties(brandDTO,Brand.class);
        brand .setId(null);
        int count = brandMapper.insertSelective(brand);
        if (count != 1){
            //新增失败，抛出异常
            new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        //新增品牌和分类中间表
        count = brandMapper.insertCategoryBrand(brand.getId(),ids);
        if (count != ids.size()){
            //新增失败，抛出异常
            new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    /**
     * 修改品牌信息
     * @param brandDTO
     * @param ids
     */
    @Transactional
    public void updateBrand(BrandDTO brandDTO, List<Long> ids) {
        Brand brand = BeanHelper.copyProperties(brandDTO,Brand.class);
        //修改品牌
        //selective玩的逻辑是属性Selective有值，才去修改，没有加selective属性没有值，会把属性设置为null
        int count = brandMapper.updateByPrimaryKey(brand);
        if (count != 1){
            //更新失败，抛出异常
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        //删除中间表数据
        count = brandMapper.deleteCategoryBrand(brand.getId());
        if(count != ids.size()){
            //新增失败，抛出异常
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        //重新插入中间表数据
        count = brandMapper.insertCategoryBrand(brand.getId(),ids);
        if (count != 1){
            //新增失败，抛出异常
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

    }

    /**
     * 删除品牌数据
     * @param bid
     */
    public void deleteBrand(Long bid) {
        //删除品牌表数据
        int count = brandMapper.deleteBrand(bid);
        if (count != 1){
            throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }

        //删除中间表数据
         count = brandMapper.deleteCategoryBrand(bid);
        if (count == 0) {
            throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }
    }

    /**
     * 根据品牌id查询品牌
     * @param id
     * @return
     */
    public BrandDTO queryById(Long id) {
        Brand brand = brandMapper.selectByPrimaryKey(id);
        if (brand == null){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyProperties(brand,BrandDTO.class);
    }

    /**
     * 根据分类id查询品牌的集合
     * @param categoryId
     * @return
     */
    public List<BrandDTO> queryBrandByCategoryId(Long categoryId) {
        List<Brand> brands = brandMapper.queryBrandByCategoryId(categoryId);
        //判断是否为空
        if (CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(brands,BrandDTO.class);
    }

    /**
     * 根据ids集合查询品牌集合
     * @param ids
     * @return
     */
    public List<BrandDTO> queryBrandByIds(List<Long> ids) {
        List<Brand> brands = brandMapper.selectByIdList(ids);
        //判断是否为空
        if (CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(brands,BrandDTO.class);
    }

    /**
     * 根据id查询品牌
     * @param id
     * @return
     */
    public BrandDTO querybrandByid(Long id) {
        Brand brand = this.brandMapper.selectByPrimaryKey(id);
        if (brand == null){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyProperties(brand,BrandDTO.class);
    }
}
